package com.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.user.common.R;
import com.user.entity.ResultResponse;
import com.user.mapper.UserMapper;
import com.user.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.user.service.RecordService;
import com.user.vo.BirthdayVo;
import com.user.vo.UserVo;
import com.usian.model.record.Recordd;
import com.usian.model.shop.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * <p>
 * 登录 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-12-17
 */
@Service
@Slf4j
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RecordService recordService;

    @Override
    public Object login(String phone, Integer verify) {
        // 查询用户
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone, phone);
        User user = userMapper.selectOne(queryWrapper);

        // 判断手机号是否存在
        if (user == null) {
            return R.error("该手机号还未注册，请先注册");
        }
        // 从 Redis 中获取验证码并进行空值检查
        int captcha = (int) redisTemplate.opsForValue().get("yanzheng");
        // 验证码一致性判断
        if (captcha == verify) {
            return R.success(user);
        } else {
            return R.error("验证码错误");
        }
    }

    @Override
    public Object insert(User user) {
        // 生成10位随机数
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 10; i++) {
            sb.append(random.nextInt(10));
        }
        String randomNumber = sb.toString();
        user.setBh(randomNumber);

//        // 从Redis中获取验证码并进行空值检查
//        Integer yanzhengma = (Integer) redisTemplate.opsForValue().get("yanzheng");
//        if (yanzhengma == null) {
//            return R.error("验证码未找到");
//        }

//        // 判断验证码是否正确
//        if (!yanzhengma.equals(user.getVerify())) {
//            return R.error("验证码错误，无法注册");
//        }

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone, user.getPhone());
        User user2 = userMapper.selectOne(queryWrapper);

        // 判断手机号是否存在
        if (user2 != null) {
            return R.error("手机号已存在，无法注册");
        }
        user.setScore(1000);
        userMapper.insert(user);
        return R.success("注册成功");
    }

    //展示商品信息
    @Override
    public List<User> findList(User user) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();

        System.out.println(user.getName());
        // 如果传入的name不为空且不为空字符串，则添加用户名的查询条件
        if (user.getName() != null && !user.getName().isEmpty()) {
            queryWrapper.eq(User::getName, user.getName());
        }
        // 如果传入的phone不为空且不为空字符串，则添加手机号的查询条件
        if (user.getPhone() != null && !user.getPhone().isEmpty()) {
            queryWrapper.eq(User::getPhone, user.getPhone());
        }
        return userMapper.selectList(queryWrapper);
    }

    @Override
    public User findById(Integer id) {
        return userMapper.selectById(id);
    }

    @Override
    public void updateUserById(String name, Integer id) {
        userMapper.updateUserById(name, id);
    }

    @Override
    public Integer findScoreId(Integer id) {
        return userMapper.findScoreId(id);
    }

    @Override
    public UserVo updateScore(UserVo userVo) {
        Integer id = userVo.getId();
        Integer score = userVo.getScore();
        int result = userMapper.updateScore(id, score);
        return userVo;
    }

    @Override
    public ResultResponse updateBirthById(BirthdayVo birthdayVo) {
        userMapper.updateBirthById(birthdayVo.getBirth(), birthdayVo.getId());
        return ResultResponse.ok();
    }

    @Override
    public ResultResponse signIn(Integer id) {
        if (id == null) {
            return ResultResponse.error().message("请先登录！！");
        }
        //根据id查看签到日期
        User user = userMapper.selectById(id);
        Date date = user.getSignTime();
        log.info("签到日期：" + date);
        if (date == null) {
            // 如果签到日期为空，则直接更新签到日期
            userMapper.updateSignTime(new Date(), id);
            Integer score = user.getScore();
            userMapper.updateScore(id, score + 1000);
            Recordd recordd = new Recordd();
            recordd.setName("签到积分奖励");
            recordd.setScore(1000);
            recordd.setDatee(new Date());
            recordd.setUid(id);
            recordService.save(recordd);
            return ResultResponse.ok().message("首次签到成功");
        }
        Date currentDate = new Date();
        long day = (currentDate.getTime() - date.getTime()) / (24 * 60 * 60 * 1000);
        if (day >= 1) {
            //如果大于一天，则更新签到日期
            userMapper.updateSignTime(currentDate, id);
            Integer score = user.getScore();
            if (score == null) {
                score = 1000;
            } else {
                score = score + 1000;
            }
            userMapper.updateScore(id, score);
            Recordd recordd = new Recordd();
            recordd.setName("签到积分奖励");
            recordd.setScore(1000);
            recordd.setDatee(new Date());
            recordd.setUid(id);
            recordService.save(recordd);
            return ResultResponse.ok().message("签到成功");
        } else {
            return ResultResponse.error().message("今日已签到");
        }
    }

    @Override
    public User find(Integer id) {
        return userMapper.selectById(id);
    }

    @Override
    public boolean updateImage(Integer id, String image) {
        return userMapper.updateImage(id, image); // 只更新头像字段
    }

    @Override
    public ResultResponse toLoginPassword(User user) {
        log.info("用户名：" + user.getPhone(), "密码：" + user.getPassword());
        // 检查用户名是否为空
        if (user.getPhone() == null || user.getPhone().isEmpty()) {
            return ResultResponse.error().message("手机号不能为空");
        }
        // 检查密码是否为空
        if (user.getPassword() == null || user.getPassword().isEmpty()) {
            return ResultResponse.error().message("密码不能为空");
        }
        // 构建查询条件，同时使用电话号码和密码
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("phone", user.getPhone()).eq("password", user.getPassword());
        // 执行查询
        User user1 = userMapper.selectOne(qw);
        // 判断查询结果
        if (user1 != null) {
            return ResultResponse.ok().data("user", user1).message("登录成功");
        } else {
            return ResultResponse.error().message("用户名或密码错误");
        }
    }

    @Override
    public ResultResponse updatePassword(User user) {
        log.info("用户名：" + user.getPhone(), "密码：" + user.getPassword());
        // 检查用户名是否为空
        if (user.getPhone() == null || user.getPhone().isEmpty()) {
            return ResultResponse.error().message("手机号不能为空");
        }
        // 检查密码是否为空
        if (user.getPassword() == null || user.getPassword().isEmpty()) {
            return ResultResponse.error().message("密码不能为空");
        }
        // 构建查询条件
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("phone", user.getPhone());// 根据电话号码查询
        User user1 = userMapper.selectOne(qw);// 执行查询
        if (user1 == null) {
            return ResultResponse.error().message("用户不存在");
        } else {
            userMapper.updatePassword(user.getPhone(), user.getPassword());
            return ResultResponse.ok().message("修改密码成功");
        }
    }

    @Override
    public void deleteUser(Integer id) {
        userMapper.deleteUser(id);
    }


    //设置交易密码
    @Override
    public ResultResponse setPayPassword(Integer uid, Integer code) {
        int result = userMapper.setPayPassword(uid, code);
        if (result > 0) {
            return ResultResponse.ok().message("设置交易密码成功");
        } else {
            return ResultResponse.ok().message("设置交易密码失败");
        }
    }

    @Override
    public ResultResponse getPayPassword(Integer id) {
        String password = userMapper.getPayPassword(id);
        return ResultResponse.ok().data("payPassword", password);
    }


}
